import { reqGetCode, reqGetLogin, reqGetUserValue, reqLogOut, reqRegister } from "@/api";
import { setToken, getToken, removeToken } from "@/utils/settoken";
const state = {
  code: "",
  token: getToken(),
  nickName: "",
};
const mutations = {
  GETCODE(state, data) {
    state.code = data;
  },
  SETTOKEN(state, token) {
    state.token = token;
  },
  SETNAME(state, name) {
    state.nickName = name;
  },
  LOGOUT(state) {
    state.token = "";
    state.nickName = "";
    removeToken();
  },
};
const actions = {
  async getCodeFun({ state, commit, dispatch }, phone) {
    let res = await reqGetCode(phone);
    if (res.code == 200) {
      commit("GETCODE", res.data);
      return "ok";
    } else {
      return Promise.reject();
    }
  },
  async registerFun({ state, commit, dispatach }, data) {
    console.log(data);
    let res = await reqRegister(data);
    if (res.code == 200) {
      return "ok";
    } else {
      return Promise.reject(res.message);
    }
  },
  async getLoginFun({ state, commit, dispatch }, data) {
    let res = await reqGetLogin(data);
    if (res.code == 200) {
      commit("SETTOKEN", res.data.token);
      setToken(res.data.token);
      return "ok";
    } else {
      return Promise.reject(res.message);
    }
  },
  async getUserValueFun({ state, commit, dispatch }) {
    let res = await reqGetUserValue();
    if (res.code == 200) {
      commit("SETNAME", res.data.nickName);
      return "ok";
    } else {
      return Promise.reject();
    }
  },
  async logOutFun({ state, commit, dispatach }) {
    let res = await reqLogOut();
    if (res.code == 200) {
      commit("LOGOUT");
    }
  },
};

export default { namespaced: true, state, mutations, actions };
